package com.shycloud.mido.opter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.feign.RemoteMemberService;
import com.shycloud.mido.member.api.vo.SmMemberTeacherApprovalNewVO;
import com.shycloud.mido.opter.api.entity.OptOperator;
import com.shycloud.mido.opter.api.entity.OrgRecommendOrg;
import com.shycloud.mido.opter.api.entity.OrgSettledCount;
import com.shycloud.mido.opter.api.vo.OptAndOrgVO;
import com.shycloud.mido.opter.api.vo.OptHardwareVO;
import com.shycloud.mido.opter.api.vo.SaleOrgListVO;
import com.shycloud.mido.opter.api.vo.SaleOrgOptListVO;
import com.shycloud.mido.opter.mapper.NewOperatorMapper;
import com.shycloud.mido.opter.mapper.OptTeacherApprovalMapper;
import com.shycloud.mido.opter.mapper.OrgRecommendOrgMapper;
import com.shycloud.mido.opter.mapper.OrgSettledCountMapper;
import com.shycloud.mido.opter.service.NewOperatorService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Xiaoxing Yu
 * @date 2020/9/4
 **/

@Service
@AllArgsConstructor
public class NewOperatorServiceImpl implements NewOperatorService {

	private OptTeacherApprovalMapper optTeacherApprovalMapper;

	private RemoteMemberService remoteMemberService;
	/** 运营商模块 mapper */
	private NewOperatorMapper operatorMapper;
	/** 机构推荐 mapper */
	private OrgRecommendOrgMapper orgRecommendOrgMapper;
	/** 结算订单业务 mapper */
	private OrgSettledCountMapper settledCountMapper;

	@Override
	public IPage<SmMemberTeacherApprovalNewVO> getTeacherApprovalPage(
			Page page, String name, String status, String optrId) {
		IPage<SmMemberTeacherApprovalNewVO> iPage = optTeacherApprovalMapper
				.getTeacherApprovalPage(page, name, status);

		List<SmMemberTeacherApprovalNewVO> approvalList = iPage.getRecords();

		if (!StringUtils.isEmpty(optrId)) {
			for (SmMemberTeacherApprovalNewVO vo : approvalList) {
				String memberId = vo.getMemberId();

				//查看用户现在归属的运营商
				Member member = remoteMemberService.memberInfo(memberId);

				if (!String.valueOf(member.getOptId()).equals(optrId)) {
					//归属的运营商不匹配，应该从list中移除
					approvalList.remove(vo);
				}
			}
		}

		return iPage;
	}


	/**
	 * 获取运营商或机构工作是列表
	 *
	 * @param type
	 * @param nameOrPhone
	 * @param page
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.opter.api.vo.OptAndOrgVO>
	 * @author nianhua.jiang
	 * @date 2020/9/25 16:25
	 **/
	@Override
	public IPage<OptAndOrgVO> getOptAndOrgList(String type, String nameOrPhone, Page page) {

		String name = StringUtils.EMPTY;
		String phone = StringUtils.EMPTY;
		//判断参数是否为电话号码
		if (StringUtils.isNumeric(nameOrPhone)) {
			phone = nameOrPhone;
		} else {
			name = nameOrPhone;
		}

		//市运营商的场合
		if ("0".equals(type)) {
			return operatorMapper.getCityOptList(page, name, phone);
		}
		//省运营商的场合
		if ("1".equals(type)) {
			return operatorMapper.getProvinceOptList(page, name, phone);
		}
		//机构工作室的场合
		if ("2".equals(type)) {
			return operatorMapper.getOrgList(page, name, phone);
		}
		if ("3".equals(type)) {
			return operatorMapper.getDistList(page, name, phone);
		}
		return null;
	}

	@Override
	public boolean actvHardWare(OptHardwareVO optHardwareVO) {

		//用户 memberId
		String memberId = optHardwareVO.getMemberId();
		//UDID
		String udid = optHardwareVO.getUdid();
		//激活码
		String actvCode = optHardwareVO.getActvCode();
		//同时开通VIP期限
		Integer vipDuration = optHardwareVO.getDuration();
		//运营商ID
		Integer optId = optHardwareVO.getOptId();

		//判断激活码是否存在
		if (operatorMapper.hasActeCode(actvCode) == 0) {
			throw new BusinessException("激活码不存在");
		}

		//判断激活码是否已被使用
		if (operatorMapper.checkActvCode(actvCode) == 1) {
			throw new BusinessException("激活码已被使用");
		}

		//开通硬件

		return true;
	}

	@Override
	public SaleOrgOptListVO getSaleOrgList(Integer orgId, Integer optId) {

		SaleOrgOptListVO saleOrgOptListVO = new SaleOrgOptListVO();

		if (optId != null) {

			//查询机构所对应的代理商信息
			//查询此代理商下的机构列表
			OptOperator optOperator = operatorMapper.selectById(optId);
			//代理商ID
			saleOrgOptListVO.setOptId(optOperator.getId());
			//代理商名称
			saleOrgOptListVO.setOptName(optOperator.getName());
			//预存未结数量
			saleOrgOptListVO.setUnPreStorageCount(optOperator.getUnPreStorageCount());

			List<SaleOrgListVO> orgListVoS = operatorMapper.getSaleOrgList(optId);

			//计算 机构【总销售】、【团队销售】标识、【结算订单】
			for (SaleOrgListVO orgVO : orgListVoS) {

				//查询此机构下是否有推荐团队
				Integer teamCount = orgRecommendOrgMapper
						.selectCount(new QueryWrapper<OrgRecommendOrg>().eq("org_id", orgVO.getOrgId()));

				if (teamCount > 0) {
					orgVO.setIsTeam("1");
				} else {
					orgVO.setIsTeam("0");
				}

				if (optOperator.getPhone().equals(orgVO.getPhone())) {
					orgVO.setIsMe("1");
				} else {
					orgVO.setIsMe("0");
				}
				//有推荐团队
				if ("1".equals(orgVO.getIsTeam())) {
					//计算团队【团队销售】 以及 【未结算】 订单
					SaleOrgListVO orgListTemp2 = operatorMapper.getSaleOrgListTemp2(orgVO.getOrgId());

					//如果此团队也有推荐团队，则【自销售】不计入总销售当中
					Integer totalSaleCount = 0;

					Integer count = orgRecommendOrgMapper
							.selectCount(new QueryWrapper<OrgRecommendOrg>().eq("recommend_org_id", orgVO.getOrgId()));
					if (count > 0) {
						//总销售 = 团队销售
						totalSaleCount = orgListTemp2.getTeamSaleTotalCount();
					} else {
						//总销售 = 团队销售 + 自销售
						totalSaleCount = orgListTemp2.getTeamSaleTotalCount() + orgVO.getMySaleTotalCount();
					}

					orgVO.setSaleTotalCount(totalSaleCount);
					//团队销售
					orgVO.setTeamSaleTotalCount(orgListTemp2.getTeamSaleTotalCount());
					//结算订单
					List<OrgSettledCount> orgSettledCounts = settledCountMapper
							.selectList(new QueryWrapper<OrgSettledCount>().eq("type", "org").eq("org_id", orgVO.getOrgId()));
					if (orgSettledCounts.size() > 0) {
						//已结算订单数量
						Integer settledCounts = orgSettledCounts.stream().mapToInt(OrgSettledCount::getOrderSettledCount).sum();
						//未结算订单 = 团队销售 - 已结算订单
						orgVO.setUnsettledCount(orgVO.getTeamSaleTotalCount() - settledCounts);
					} else {
						orgVO.setUnsettledCount(orgVO.getTeamSaleTotalCount());
					}
				}
				//无推荐团队
				else {
					if (orgVO.getParentOrgId() != null) {
						//团队总销售 = 0
						orgVO.setSaleTotalCount(0);
					} else {
						orgVO.setSaleTotalCount(orgVO.getMySaleTotalCount());
					}
				}
			}
			//排序
			List<SaleOrgListVO> orgListResult = orgListVoS.stream().sorted((n1, n2) -> n2.getIsMe().compareTo(n1.getIsMe()))
					.collect(Collectors.toList());
			//存入机构信息
			saleOrgOptListVO.setOrgList(orgListResult);
			//计算代理商总销售 = 各个机构的总销售之和
			saleOrgOptListVO.setSaleTotalCount(orgListVoS.stream().mapToInt(SaleOrgListVO::getSaleTotalCount).sum());
			//计算此代理商与总部的未结算订单
			List<OrgSettledCount> orgSettledCounts = settledCountMapper
					.selectList(new QueryWrapper<OrgSettledCount>().eq("type", "opt").eq("opt_id", optId));

			if (orgSettledCounts.size() > 0) {
				//已结算订单数量
				Integer settledCounts = orgSettledCounts.stream().mapToInt(OrgSettledCount::getOrderSettledCount).sum();
				//未结算订单 = 总销售 - 已结算订单
				saleOrgOptListVO.setUnsettledCount(saleOrgOptListVO.getSaleTotalCount() - settledCounts);
			} else {
				saleOrgOptListVO.setUnsettledCount(saleOrgOptListVO.getSaleTotalCount());
			}

			return saleOrgOptListVO;
		}
		//机构点击【销售统计】或 代理商选择查看机构下的【团队销售】时
		else if (orgId != null) {
			//查询机构下推荐机构
			List<SaleOrgListVO> orgList = operatorMapper.getSaleRecommendOrgList(orgId);
			//初始化响应体
			SaleOrgOptListVO saleOrgOptListVoOrg = new SaleOrgOptListVO();
			//推荐机构销售情况列表
			saleOrgOptListVoOrg.setOrgList(orgList);
			//计算总单数
			saleOrgOptListVoOrg.setSaleTotalCount(orgList.stream().mapToInt(SaleOrgListVO::getSaleTotalCount).sum());
			//计算未结算订单数量
			List<OrgSettledCount> orgSettledCounts = settledCountMapper
					.selectList(new QueryWrapper<OrgSettledCount>().eq("type", "org").eq("org_id", orgId));
			if (orgSettledCounts.size() > 0) {
				//已结算订单数量
				Integer settledCounts = orgSettledCounts.stream().mapToInt(OrgSettledCount::getOrderSettledCount).sum();
				//未结算订单 = 总销售 - 已结算订单
				saleOrgOptListVoOrg.setUnsettledCount(saleOrgOptListVoOrg.getSaleTotalCount() - settledCounts);
			} else {
				saleOrgOptListVoOrg.setUnsettledCount(saleOrgOptListVoOrg.getSaleTotalCount());
			}
			//机构名称
			saleOrgOptListVoOrg.setOrgName(operatorMapper.getOrgNameByOrgId(orgId));
			return saleOrgOptListVoOrg;
		} else {
			throw new BusinessException("optId 和 orgId 至少传一项");
		}

	}

}
